use std::io::{self,Write};
use crate::core::camera::*;
use crate::core::vec3::Color3;

pub fn write_color(out: &mut io::Stdout, pixel_color: Color3, samples_per_pixel: &f64) ->io::Result<()> {
    // Write the translated [0,255] value of each color component.

    let mut r = pixel_color.get_x();
    let mut g = pixel_color.get_y();
    let mut b = pixel_color.get_z();

    // Divide the color by the number of samples
    // let scale = 1_f64 / samples_per_pixel;
    // r *= scale;
    // g *= scale;
    // b *= scale;
    // Divide the color by the number of samples and gamma-correct for gamma=2.0.
    let scale = 1_f64 / samples_per_pixel;
    r = (scale * r).sqrt();
    g = (scale * g).sqrt();
    b = (scale * b).sqrt();
    
    writeln!(out, "{} {} {}",
        (255.999 * clamp(r, 0_f64, 0.999_f64)) as i32,
        (255.999 * clamp(g, 0_f64, 0.999_f64)) as i32,
        (255.999 * clamp(b, 0_f64, 0.999_f64)) as i32
    ).unwrap();
    Ok(())
}